package com.homedo.odin.solution.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.homedo.core.common.base.dto.Meta;
import com.homedo.core.common.base.service.BaseService;
import com.homedo.core.common.exception.BizException;
import com.homedo.core.common.util.BeanUtils;
import com.homedo.odin.solution.contract.mng.ColumnTagPageRequestBean;
import com.homedo.odin.solution.dao.ColumnTagMapper;
import com.homedo.odin.solution.dao.SpecialColumnMapper;
import com.homedo.odin.solution.enumcode.basic.DeleteEnum;
import com.homedo.odin.solution.enumcode.basic.IsUseEnum;
import com.homedo.odin.solution.model.entity.ColumnTag;
import com.homedo.odin.solution.model.request.mng.tag.ColumnTagPageResponseBean;
import com.homedo.odin.solution.model.request.mng.tag.ColumnTagRequestBean;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p> 标签 服务实现类 </p>
 *
 * @author HarveyDing
 * @since 2018-03-08
 */
@Service
public class ColumnTagServiceImpl extends BaseService<ColumnTagMapper, ColumnTag> {

    @Autowired
    private SpecialColumnMapper specialColumnMapper;

    /************************************张磊Start************************************/

    /**
     * OMS_新增栏目标签
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertColumnTag(ColumnTagRequestBean requestBean) {
        //获取该标签，不管使用状态，删除状态
        if (StringUtils.isBlank(requestBean.getName())) {
            throw new BizException(Meta.CODE_451.getCode(), "标签名称不能为空");
        }

        List<ColumnTag> columnTagList = baseMapper.selectByName(requestBean.getName(), null, null);
        Map<Integer, List<ColumnTag>> groupMap = getFilterStatusMapTag(columnTagList);

        if (groupMap != null) {
            List<ColumnTag> delList = groupMap.get(DeleteEnum.IS_DEL.getDbValue());
            updateExistTag(requestBean, delList);
        } else {
            ColumnTag columnTag = new ColumnTag();
            convent(requestBean, columnTag);
            baseMapper.insert(columnTag);
        }
    }

    /**
     * OMS_修改栏目标签
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateTag(ColumnTagRequestBean requestBean) {
        if (StringUtils.isBlank(requestBean.getOperator())) {
            throw new BizException(Meta.CODE_451.getCode(), "操作人不能为空");
        }

        ColumnTag dbBean = baseMapper.selectById(requestBean.getTagId());
        if (dbBean == null) {
            throw new BizException(Meta.CODE_451.getCode(), "修改失败，该标签不存在");
        }

        if (StringUtils.isNotBlank(requestBean.getName())) {
            //获取该标签，不管使用状态，删除状态
            List<ColumnTag> columnTagList = baseMapper.selectByName(requestBean.getName(), null, null);
            Map<Integer, List<ColumnTag>> groupMap = getFilterStatusMapTag(columnTagList);

            if (groupMap != null) {
                List<ColumnTag> delList = groupMap.get(DeleteEnum.IS_DEL.getDbValue());
                updateExistTag(requestBean, delList);
            } else {
                //未重名数据，直接修改
                dbBean.setName(requestBean.getName());
            }
        } else if (requestBean.getSort() != null) {
            //排序修改
            dbBean.setSort(requestBean.getSort());
        } else {
            throw new BizException(Meta.CODE_451.getCode(), "非法操作，标签修改目前只支持排序 名称操作");
        }
        dbBean.setLastModifiedTime(new Date());
        dbBean.setCreateUserName(requestBean.getOperator());
        baseMapper.updateById(dbBean);
    }

    /**
     * OMS_删除栏目标签
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteColumnTag(Integer tagId, String operator) {
        ColumnTag dbBean = baseMapper.selectById(tagId);
        if (dbBean == null) {
            throw new BizException(Meta.CODE_451.getCode(), "删除失败，该标签不存在");
        }

        //清除绑定的栏目tagid，给与默认值
        Set<Integer> set = new HashSet<>();
        set.add(dbBean.getId());
        Integer count = specialColumnMapper.selectCountByTagIds(set);
        if (count > 0) {
            specialColumnMapper.updateTagIdByTagIds(set, 0);
        }

        dbBean.setStatus(DeleteEnum.IS_DEL.getDbValue());
        dbBean.setIsUse(IsUseEnum.NO.getDbValue());
        dbBean.setLastModifiedTime(new Date());
        dbBean.setCreateUserName(operator);
        baseMapper.updateById(dbBean);
    }


    /**
     * OMS_条件分页栏目标签列表
     *
     * @param requestBean
     */
    private final String DESC = "desc";
    private final String ASC = "asc";
    private final String SORT = "sort";
    private final String UPDATE_TIME = "last_modified_time";

    public ColumnTagPageResponseBean queryByParamList(ColumnTagPageRequestBean requestBean) {
        StringBuilder sb = new StringBuilder();
        if (StringUtils.isNotBlank(requestBean.getSortType())) {
            if (!DESC.equals(requestBean.getSortType()) && !ASC.equals(requestBean.getSortType())) {
                throw new BizException(Meta.CODE_451.getCode(), "排序信息不合法 降序：DESC  升序：ASC");
            }
            sb.append(SORT).append(" ").append(requestBean.getSortType());
        } else {
            sb.append(UPDATE_TIME).append(" ").append(DESC);
        }
        PageHelper.startPage(requestBean.getPageNum(), requestBean.getPageSize(), sb.toString());
        PageInfo<ColumnTag> pageInfo = new PageInfo(
                baseMapper.queryByParamList(requestBean.getIsUse(), DeleteEnum.NOT_DEL.getDbValue()));
        return BeanUtils.transfrom(ColumnTagPageResponseBean.class, pageInfo);
    }


    /**
     * MngCommonDataController公共信息  获取所有标签信息
     */
    public List<ColumnTag> queryAllTag(Integer isUse, Integer isdel) {
        return baseMapper.queryAllTag(isUse, isdel);
    }

    /**
     * 转换请求对象与标签对象 暂时不用工具拷贝，字段不同一，有可能字段为NULL，数据库字段不能为Null
     */
    private void convent(ColumnTagRequestBean requestBean, ColumnTag columnTag) {
        columnTag.setStatus(DeleteEnum.NOT_DEL.getDbValue());
        columnTag.setIsUse(IsUseEnum.NO.getDbValue());
        columnTag.setName(requestBean.getName());
        columnTag.setCreateUserName(requestBean.getOperator());
        columnTag.setSort(0);
        Date date = new Date();
        columnTag.setCreateTime(date);
        columnTag.setLastModifiedTime(date);
    }

    /**
     * 修改第一条重名数据，删除其他重名数据
     */
    private void updateExistTag(ColumnTagRequestBean requestBean, List<ColumnTag> delList) {
        if (CollectionUtils.isNotEmpty(delList) && delList.size() > 0) {
            ColumnTag columnTag = delList.get(0);
            convent(requestBean, columnTag);
            //多余的重复的选择直接删除，同一名称只允许一条数据
            Set<Integer> set = delList.stream().filter(bean -> !bean.getId().equals(columnTag.getId()))
                    .map(bean -> bean.getId()).collect(Collectors.toSet());
            if (CollectionUtils.isNotEmpty(set)) {
                baseMapper.deleteColumnTagByIds(set);
                //获取在使用这些tagId的栏目
                Integer count = specialColumnMapper.selectCountByTagIds(set);
                if (count > 0) {
                    //有在使用把新标签设置状态， 栏目修改为新标签的Id
                    columnTag.setIsUse(IsUseEnum.YES.getDbValue());
                    //并把栏目绑定这些标签的  修改为唯一的这一条新标签
                    specialColumnMapper.updateTagIdByTagIds(set, columnTag.getId());
                }
            }
            baseMapper.updateById(columnTag);
        }
    }

    /**
     * 根据删除状态分组，并检查是否重名数据存在
     */
    private Map<Integer, List<ColumnTag>> getFilterStatusMapTag(List<ColumnTag> columnTagList) {
        Map<Integer, List<ColumnTag>> groupMap = null;
        if (CollectionUtils.isNotEmpty(columnTagList)) {
            //根据删除状态分组
            groupMap = columnTagList.stream().filter(bean -> bean != null)
                    .collect(Collectors.groupingBy(bean -> bean.getStatus()));
            List<ColumnTag> notDelList = groupMap.get(DeleteEnum.NOT_DEL.getDbValue());
            //未删除分组存在数据
            if (CollectionUtils.isNotEmpty(notDelList) && notDelList.size() > 0) {
                throw new BizException(Meta.CODE_451.getCode(), "该标签名已存在");
            }
        }
        return groupMap;
    }

    /************************************张磊End************************************/


    public ColumnTag getColumnTag(Integer id) {
        ColumnTag tag = new ColumnTag();
        tag.setId(id);
        tag.setStatus(0);
        return baseMapper.selectOne(tag);
    }
}
